PyTure Docs
Advanced Usage
Unlock the full potential of PyTure with advance examples.
1. Custom Metadata & Dynamic Fields
PyTure allows you to attach custom attributes when capturing events. This is useful for tracking additional details like browser, device, or session-specific tags.
Example Usage:
session = PyTure()
# Capture a purchase event with custom fields
session.capture(
action="purchase",
user="Bob",
amount=49.99,
currency="USD",
device="mobile"
)
✅ PyTure automatically includes these custom keys in JSON and CSV exports, so all your dynamic metadata is preserved.
2. Filtering & Querying Captures
PyTure allows you to analyze subsets of captured data before exporting.
You can filter events by keys like user
or action
using Python’s list comprehension.
Example Usage:
session = PyTure()
# Capture some events
session.capture(action="login", user="Alice")
session.capture(action="click", element="button", user="Alice")
session.capture(action="purchase", user="Bob", amount=49.99)
# Filter captures for a specific user
alice_events = [c for c in session.buffer if c.get("user") == "Alice"]
print(alice_events)
# Output: [{'action': 'login', 'user': 'Alice'}, {'action': 'click', 'element': 'button', 'user': 'Alice'}]
✅ You can filter by any field present in your captured events. This filtered data can then be saved or exported separately.
3. Multiple Sessions & Parallel Tracking
PyTure allows you to create multiple independent sessions to track different flows simultaneously. Each session has its own buffer, but all captured events still append to the global capture list.
Example Usage:
from pyture import PyTure
# Create separate sessions
auth_session = PyTure()
ui_session = PyTure()
# Capture events in different sessions
auth_session.capture(action="login", user="Alice")
ui_session.capture(action="click", element="settings", user="Alice")
# Each session has its own buffer
print(auth_session.buffer)
# Output: [{'action': 'login', 'user': 'Alice'}]
print(ui_session.buffer)
# Output: [{'action': 'click', 'element': 'settings', 'user': 'Alice'}]
# All captures still go to the global capture list for saving/exporting
4. Persistent Storage (Save & Load Sessions)
PyTure allows you to save session data to a JSON file and reload it later. This is useful for long-running applications or when you want to analyze captured data later.
Example Usage:
from pyture import PyTure
# Create a session and capture some events
session = PyTure()
session.capture(action="login", user="Alice")
session.capture(action="click", element="button", user="Alice")
# Save the session to a JSON file
session.save("session_data.json")
# Later, load the saved session into a new PyTure object
new_session = PyTure()
new_session.load("session_data.json")
print(new_session.buffer)
# Output: [{'action': 'login', 'user': 'Alice'}, {'action': 'click', 'element': 'button', 'user': 'Alice'}]
✅ You can now persist session data across program runs.
Note: In your current library, loading a file only populates the instance's buffer
, it does not automatically append to the global _captures
.
5. Export Formats (Beyond CSV)
PyTure allows exporting captured data not only to CSV, but also to JSON for further analysis. You can also convert captures to a Pandas DataFrame for more advanced analytics or visualization.
Example Usage:
from pyture import PyTure
import pandas as pd
# Create session and capture some events
session = PyTure()
session.capture(action="login", user="Alice")
session.capture(action="purchase", user="Bob", amount=49.99)
# Export to JSON file
session.save("captures.json", mode="full")
# Convert captures to a Pandas DataFrame
df = pd.DataFrame(session.buffer) # or use _captures for global captures
print(df.head())
✅ This allows deeper analysis using Python’s data science tools like Pandas, Matplotlib, or Seaborn. JSON export preserves all timestamps, session IDs, and custom fields.
6. Integrations with Analytics / Dashboards
PyTure captures can easily be integrated with analytics tools or dashboards for visualization and deeper analysis. By converting captured data into a Pandas DataFrame, you can summarize, filter, or plot events using libraries like Matplotlib or Seaborn.
Example Usage:
from pyture import PyTure
import pandas as pd
import matplotlib.pyplot as plt
# Create a PyTure session
session = PyTure()
# Capture events with custom metadata
session.capture(action="login", user="Alice", device="desktop")
session.capture(action="click", element="button", user="Alice", device="desktop")
session.capture(action="purchase", user="Bob", amount=49.99, currency="USD", device="mobile")
session.capture(action="logout", user="Alice", device="desktop")
session.capture(action="login", user="Bob", device="mobile")
session.capture(action="click", element="link", user="Bob", device="mobile")
# Convert session buffer to Pandas DataFrame
df = pd.DataFrame(session.buffer)
# Preview DataFrame
print(df)
"""
Output example:
action user element amount currency device
0 login Alice NaN NaN NaN desktop
1 click Alice button NaN NaN desktop
2 purchase Bob NaN 49.99 USD mobile
3 logout Alice NaN NaN NaN desktop
4 login Bob NaN NaN NaN mobile
5 click Bob link NaN NaN mobile
"""
# Example: Count actions per user
action_counts = df.groupby("user")["action"].count()
print(action_counts)
# Alice 3
# Bob 3
# Example: Plot a bar chart of actions per user
action_counts.plot(kind="bar", title="Number of Actions per User")
plt.xlabel("User")
plt.ylabel("Action Count")
plt.show()
# Example: Filter purchases and plot amounts
purchases = df[df["action"] == "purchase"]
plt.bar(purchases["user"], purchases["amount"])
plt.title("Purchase Amounts per User")
plt.xlabel("User")
plt.ylabel("Amount (USD)")
plt.show()
✅ Using Pandas and Matplotlib, you can visualize captured events, analyze user behavior, and integrate PyTure data into dashboards or reports. All custom metadata fields are preserved, making it easy to filter, group, and plot.
7. Advanced Event Structures
PyTure allows capturing hierarchical or nested event data using Python dictionaries. This is useful when events have multiple related attributes, such as form submissions, multi-step actions, or complex metadata.
Example Usage:
from pyture import PyTure
# Create a session
session = PyTure()
# Capture a form submission with nested details
session.capture(
action="form_submit",
user="Alice",
details={
"fields": ["name", "email", "password"],
"valid": True,
"submitted_at": "2025-08-18T12:45:00"
}
)
# Capture a multi-step action
session.capture(
action="checkout",
user="Bob",
steps=[
{"step": "add_to_cart", "item": "Laptop"},
{"step": "payment", "method": "Credit Card"},
{"step": "confirmation", "status": "success"}
]
)
# Access captured buffer
print(session.buffer)
"""
Output example:
[
{'action': 'form_submit', 'user': 'Alice', 'details': {'fields': ['name', 'email', 'password'], 'valid': True, 'submitted_at': '2025-08-18T12:45:00'}},
{'action': 'checkout', 'user': 'Bob', 'steps': [{'step': 'add_to_cart', 'item': 'Laptop'}, {'step': 'payment', 'method': 'Credit Card'}, {'step': 'confirmation', 'status': 'success'}]}
]
"""
✅ PyTure preserves nested structures in JSON exports. For CSV exports, nested data may be flattened or represented as strings, so JSON is recommended for complex event structures.
8. Performance Tips & Best Practices
When using PyTure for large or long-running applications, consider the following tips to optimize performance and memory usage.
1. Minimize memory usage:
PyTure stores all captured events in memory (`buffer` per instance and global `_captures`). For large volumes, avoid keeping unnecessary intermediate data.
# Example: capture only required fields
session.capture(action="click", element="button", user="Alice")
2. Batch captures vs. single-line captures:
If multiple events occur together, you can capture them in a loop to reduce repetitive code.
events = [
{"action": "login", "user": "Alice"},
{"action": "click", "element": "settings", "user": "Alice"},
{"action": "logout", "user": "Alice"}
]
for e in events:
session.capture(**e)
3. Clear sessions regularly:
To free up memory and start fresh, use the .clear()
method.
session.clear()
# Output (if mode='dev'): [Cleared] Capture buffer is now empty.
4. Save & export periodically:
For very large sessions, periodically saving to JSON or CSV ensures data persistence and reduces memory footprint.
# Save periodically
session.save("session_data.json")
session.export_csv("captures.csv")
✅ Following these practices ensures PyTure remains efficient, even for high-volume or long-term tracking applications.